<template>
  <view class="recharge-container">
    <!-- 顶部房间名称/电表名称 -->
    <view class="room-title">{{ roomInfo.roomName || '房间电表' }}</view>
    
    <!-- 电量信息卡片 -->
    <view class="electricity-card">
      <view class="electricity-info">
        <view class="info-label">剩余金额</view>
      </view>
      <view class="electricity-info">
        <view class="info-value">{{ roomInfo.remainingElectricity || 0 }} 元</view>
        <view class="info-label">单价：{{ roomInfo.electricityPrice || 1 }} 元/度</view>
      </view>
    </view>
    
    <!-- 充值金额选择 -->
    <view class="recharge-amount-section">
      <view class="section-title">充值金额</view>
      <view class="amount-options">
        <view 
          v-for="(item, index) in amountOptions" 
          :key="index"
          class="amount-option"
          :class="{ active: selectedAmount === item.value && !isCustomAmount }"
          @click="selectAmount(item.value)"
        >
          {{ item.label }}
        </view>
        <view class="amount-option custom-option" :class="{ active: isCustomAmount }">
          <template v-if="!isCustomAmount">
            <text @click="enableCustomAmount">自定义</text>
          </template>
          <template v-else>
            <input 
              type="digit" 
              v-model="customAmount" 
              class="custom-input"
              @blur="validateCustomAmount"
              @input="onCustomAmountInput"
              focus
            />
          </template>
        </view>
      </view>
    </view>
    
    <!-- 分割线 -->
    <view class="divider"></view>
    
    <!-- 充值按钮 -->
    <view class="recharge-button-container">
      <button class="recharge-button" @click="handleRecharge">充值</button>
    </view>
  </view>
</template>

<script>
import { rechargeElectricity } from '@/api/device/index';
import { greet } from '@/api/login.js'
import { checkPaymentStatus } from '@/utils/common.js'

export default {
  data() {
    return {
      roomInfo: {
        roomId: '',
        roomName: '',
        remainingElectricity: 0,
        electricityPrice: 0,
        electricityMeterId: ''
      },
      amountOptions: [
        { label: '50元', value: 50 },
        { label: '100元', value: 100 },
        { label: '200元', value: 200 },
        { label: '500元', value: 500 },
        { label: '1000元', value: 1000 }
      ],
      selectedAmount: 50,
      isCustomAmount: false,
      customAmount: ''
    };
  },
  onLoad(options) {
    // 获取路由参数中的房间ID
    if (options.roomId) {
      this.roomInfo.roomId = options.roomId;
      this.roomInfo.roomName = options.name;
      this.roomInfo.remainingElectricity = options.remainAmount;
      this.roomInfo.electricityMeterId = options.electricityMeterId;
    }
  },
  methods: {
    
    // 选择充值金额
    selectAmount(amount) {
      this.selectedAmount = amount;
      this.isCustomAmount = false;
    },
    
    // 启用自定义金额输入
    enableCustomAmount() {
      this.isCustomAmount = true;
      this.customAmount = '';
    },
    
    // 验证自定义金额
    validateCustomAmount() {
      if (this.customAmount) {
        const amount = parseFloat(this.customAmount);
        if (!isNaN(amount) && amount > 0) {
          this.selectedAmount = amount;
        } else {
          uni.showToast({
            title: '请输入有效金额',
            icon: 'none'
          });
          this.customAmount = '';
        }
      } else {
        this.isCustomAmount = false;
        this.selectedAmount = 50; // 默认选中第一个选项
      }
    },
    
    // 自定义金额输入处理
    onCustomAmountInput(e) {
      // 限制只能输入数字和小数点
      const value = e.detail.value;
      this.customAmount = value.replace(/[^\d.]/g, '');
    },
    
    // 处理充值
    async handleRecharge() {
      const amount = this.isCustomAmount ? parseFloat(this.customAmount) : this.selectedAmount;
      
      if (!amount || amount <= 0) {
        uni.showToast({
          title: '请选择或输入有效的充值金额',
          icon: 'none'
        });
        return;
      }
      
      try {
        uni.showLoading({
          title: '充值中...'
        });
        uni.login({
          success: async (res) => {
            if (res.code) {
              let greetRes = await greet(res.code)
              let openId = greetRes.data.openid
              const orderRes = await rechargeElectricity({
                electricityMeterId: this.roomInfo.electricityMeterId,
                money: amount,
                openId: openId
              });

              // 调起微信支付
              uni.requestPayment({
                provider: 'wxpay',
                timeStamp: orderRes.data.timeStamp,
                nonceStr: orderRes.data.nonceStr,
                package: orderRes.data.package,
                signType: orderRes.data.signType,
                paySign: orderRes.data.paySign,
                success: async (res) => {
                  // 支付成功后轮询订单状态
                  let isSuccess = await checkPaymentStatus(0, orderRes.data.orderNo)
                  if (isSuccess) {
                    uni.showToast({
                    title: '充值成功',
                    icon: 'success'
                  })
                  uni.hideLoading();
                  // 返回上一页并通知刷新
                  const pages = getCurrentPages();
                  const prevPage = pages[pages.length - 2]; // 获取上一页实例
                  
                  if (prevPage && prevPage.getAssociatedDevice) {
                    // 设置标记，表示需要刷新
                    prevPage.$vm.needRefresh = true;
                  }
                  // 延迟返回，确保提示显示完成
                  setTimeout(() => {
                    uni.navigateBack({
                      success: () => {
                        // 通过事件总线通知上一页刷新
                        uni.$emit('refreshDeviceInfo');
                      }
                    });
                  }, 500); 
                  }
                },
                fail: (err) => {
                  console.error('充值失败:', err)
                  uni.showToast({
                    title: '充值失败，请重试',
                    icon: 'none'
                  })
                },
                complete: () => {
                  uni.hideLoading();
                }
              })
            }
          }
        })
        
      } catch (error) {
        uni.hideLoading();
        uni.showToast({
          title: '充值失败，请重试',
          icon: 'none'
        });
        console.error('充值失败:', error);
      }
    },
  }
};
</script>

<style lang="scss" scoped>
.recharge-container {
  padding: 30rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.room-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 30rpx;
}

.electricity-card {
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  margin-bottom: 40rpx;
}

.electricity-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.info-label {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.info-value {
  font-size: 40rpx;
  font-weight: bold;
  color: #333;
}

.recharge-amount-section {
  margin-bottom: 40rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.amount-options {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.amount-option {
  width: 30%;
  height: 80rpx;
  background-color: #ffffff;
  border-radius: 8rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 20rpx;
  font-size: 28rpx;
  color: #333;
  border: 1px solid #e0e0e0;
}

.amount-option.active {
  background-color: #f0f8ff;
  border-color: #1989fa;
  color: #1989fa;
}

.custom-input {
  width: 100%;
  height: 100%;
  text-align: center;
  font-size: 28rpx;
}

.divider {
  height: 1rpx;
  background-color: #e0e0e0;
  margin: 20rpx 0 40rpx;
}

.recharge-button-container {
  padding: 0 40rpx;
}

.recharge-button {
  width: 100%;
  height: 90rpx;
  background-color: #1989fa;
  color: #ffffff;
  border-radius: 45rpx;
  font-size: 32rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
